<template>
  <div class="problem-upload-container">
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h2>上传题目</h2>
          <div class="upload-steps">
            <el-steps :active="activeStep" finish-status="success" simple>
              <el-step title="题目信息" />
              <el-step title="示例数据" />
              <el-step title="测试数据" />
            </el-steps>
          </div>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="problemForm" 
        :rules="rules" 
        label-width="120px" 
        class="problem-form"
        v-loading="loading"
      >
        <!-- 步骤1: 基本信息 -->
        <div v-show="activeStep === 1">
          <h3 class="form-section-title">基本信息</h3>
          
          <el-form-item label="题目名称" prop="title">
            <el-input v-model="problemForm.title" placeholder="请输入题目名称" />
          </el-form-item>
          
          <el-form-item label="题目难度" prop="difficulty">
            <el-select v-model="problemForm.difficulty" placeholder="请选择难度">
              <el-option label="简单" :value="0" />
              <el-option label="中等" :value="1" />
              <el-option label="困难" :value="2" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="题目标签" prop="tag">
            <el-select 
              v-model="selectedTags" 
              multiple 
              filterable 
              allow-create 
              default-first-option
              placeholder="请选择或创建标签"
              @change="handleTagsChange"
            >
              <el-option 
                v-for="tag in availableTags" 
                :key="tag" 
                :label="tag" 
                :value="tag" 
              />
            </el-select>
            <div class="form-tip">多个标签用逗号分隔，如：数组,字符串,动态规划</div>
          </el-form-item>
          
          <el-form-item label="题目描述" prop="content">
            <el-input 
              v-model="problemForm.content" 
              type="textarea" 
              :rows="6" 
              placeholder="请输入题目描述"
            />
          </el-form-item>
          
          <!-- 限制条件 -->
          <h3 class="form-section-title">限制条件</h3>
          
          <el-form-item label="时间限制" prop="timeLimit">
            <el-input-number 
              v-model="timeLimit" 
              :min="0.1" 
              :max="10" 
              :step="0.1" 
              :precision="1"
              @change="handleTimeLimitChange"
            />
            <span class="unit-label">秒</span>
            <div class="form-tip">单位：秒，内部会转换为纳秒</div>
          </el-form-item>
          
          <el-form-item label="内存限制" prop="memoryLimit">
            <el-input-number 
              v-model="memoryLimit" 
              :min="1" 
              :max="1024" 
              :step="1"
              @change="handleMemoryLimitChange"
            />
            <span class="unit-label">MB</span>
            <div class="form-tip">单位：MB，内部会转换为字节</div>
          </el-form-item>
        </div>
        
        <!-- 步骤2: 示例数据 -->
        <div v-show="activeStep === 2">
          <h3 class="form-section-title">示例数据</h3>
          <div class="form-tip mb-12">
            <el-alert
              title="请使用JSON格式填写示例数据，键值对的键名必须成对出现，示例输入以in开头，输出以out开头"
              type="info"
              :closable="false"
              show-icon
            >
              <div class="json-example">
                <div class="json-example-title">输入示例:</div>
                <pre>{"in1": [1, 2, 3], "in2": [4, 5, 6]}</pre>
                <div class="json-example-title">输出示例:</div>
                <pre>{"out1": [3], "out2": [15]}</pre>
              </div>
            </el-alert>
          </div>
          
          <el-form-item label="输入示例" prop="exampleCin">
            <el-input 
              v-model="problemForm.exampleCin" 
              type="textarea" 
              :rows="6" 
              placeholder='{"in1": [1, 2], "in2": [3, 4]}'
            />
          </el-form-item>
          
          <el-form-item label="输出示例" prop="exampleOut">
            <el-input 
              v-model="problemForm.exampleOut" 
              type="textarea" 
              :rows="6" 
              placeholder='{"out1": [3], "out2": [7]}'
            />
          </el-form-item>
        </div>
        
        <!-- 步骤导航按钮 -->
        <div class="step-actions">
          <el-button v-if="activeStep > 1" @click="prevStep">上一步</el-button>
          <el-button v-if="activeStep < 2" type="primary" @click="nextStep">下一步</el-button>
          <el-button v-if="activeStep === 2" type="success" @click="submitForm">提交题目</el-button>
          <el-button @click="resetForm">重置表单</el-button>
        </div>
      </el-form>
      
      <!-- 步骤3: 测试数据上传 -->
      <div class="test-data-upload" v-show="activeStep === 3">
        <h3 class="form-section-title">测试数据上传</h3>
        <el-alert
          title="题目创建成功，现在您可以上传评测用的测试数据"
          type="success"
          :closable="false"
          show-icon
          class="mb-12"
        />
        
        <div class="current-problem-id">
          <span>当前题目ID: <strong>{{ problemId }}</strong></span>
          <el-button type="primary" size="small" @click="resetProblemId">更改ID</el-button>
        </div>
        
        <el-form :model="testDataForm" label-width="120px">
          <el-form-item label="输入数据">
            <el-input 
              v-model="testDataForm.input" 
              type="textarea" 
              :rows="6" 
              placeholder='{"test1": [1, 2, 3], "test2": [4, 5, 6]}'
            />
          </el-form-item>
          
          <el-form-item label="输出数据">
            <el-input 
              v-model="testDataForm.output" 
              type="textarea" 
              :rows="6" 
              placeholder='{"test1": [6], "test2": [15]}'
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="uploadTestData" :disabled="!problemId">
              上传测试数据
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 继续上传按钮 -->
        <div class="upload-more-actions">
          <el-button @click="continueUpload">继续上传题目</el-button>
          <el-button type="success" @click="goToProblemsList">查看题目列表</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter } from 'vue-router';
import { useUserStore } from '../store/user';
import request from '../utils/request';
import { getLatestProblemId, getNextProblemId } from '../api/problem';

// 路由
const router = useRouter();
const userStore = useUserStore();

// 表单引用
const formRef = ref<FormInstance>();

// 步骤控制
const activeStep = ref(1);

// 数据状态
const loading = ref(false);
const problemId = ref<number | null>(null);
const timeLimit = ref(1.0); // 秒
const memoryLimit = ref(100); // MB
const selectedTags = ref<string[]>([]);

// 可用标签
const availableTags = [
  '数组', '哈希表', '字符串', '排序', '双指针', 
  '动态规划', '贪心', '树', '链表', '图', '递归', 
  '分治', '回溯', '广度优先搜索', '深度优先搜索'
];

// 表单数据
const problemForm = reactive({
  title: '',
  difficulty: 0,
  tag: '',
  content: '',
  timeLimit: 1000000000, // 1秒，单位纳秒
  memoryLimit: 104857600, // 100MB，单位字节
  exampleCin: '',
  exampleOut: '',
  poster: '',
  id: 0 // 这将在提交时自动生成
});

// 测试数据表单
const testDataForm = reactive({
  pid: 0,
  input: '',
  output: ''
});

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入题目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '题目名称长度应在2到50个字符之间', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择题目难度', trigger: 'change' }
  ],
  tag: [
    { required: true, message: '请选择至少一个标签', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入题目描述', trigger: 'blur' },
    { min: 10, message: '题目描述不能少于10个字符', trigger: 'blur' }
  ],
  exampleCin: [
    { required: true, message: '请输入示例输入数据', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        try {
          if (value) {
            JSON.parse(value);
          }
          callback();
        } catch (error) {
          callback(new Error('输入数据必须是有效的JSON格式'));
        }
      }, 
      trigger: 'blur' 
    }
  ],
  exampleOut: [
    { required: true, message: '请输入示例输出数据', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        try {
          if (value) {
            JSON.parse(value);
          }
          callback();
        } catch (error) {
          callback(new Error('输出数据必须是有效的JSON格式'));
        }
      }, 
      trigger: 'blur' 
    }
  ]
});

// 处理步骤导航
const nextStep = async () => {
  if (!formRef.value) return;

  try {
    // 根据当前步骤验证相应的表单项
    if (activeStep.value === 1) {
      await formRef.value.validateField(['title', 'difficulty', 'tag', 'content']);
    } else if (activeStep.value === 2) {
      await formRef.value.validateField(['exampleCin', 'exampleOut']);
    }
    
    // 进入下一步
    activeStep.value++;
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error('请先完成当前步骤的必填项');
  }
};

const prevStep = () => {
  if (activeStep.value > 1) {
    activeStep.value--;
  }
};

// 处理标签变更
const handleTagsChange = () => {
  problemForm.tag = selectedTags.value.join(',');
};

// 处理时间限制变更（秒 -> 纳秒）
const handleTimeLimitChange = (value: number) => {
  problemForm.timeLimit = Math.round(value * 1000000000); // 转换为纳秒
};

// 处理内存限制变更（MB -> 字节）
const handleMemoryLimitChange = (value: number) => {
  problemForm.memoryLimit = value * 1024 * 1024; // 转换为字节
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
    selectedTags.value = [];
    timeLimit.value = 1.0;
    memoryLimit.value = 100;
    problemForm.timeLimit = 1000000000;
    problemForm.memoryLimit = 104857600;
    problemId.value = null;
    activeStep.value = 1;
  }
};

// 继续上传
const continueUpload = () => {
  resetForm();
  activeStep.value = 1;
};

// 前往题目列表
const goToProblemsList = () => {
  router.push('/problems');
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      
      try {
        // 设置当前用户为题目发布者
        if (userStore.userInfo?.username) {
          problemForm.poster = userStore.userInfo.username;
        }
        
        // 尝试预先获取下一个题目ID
        const nextId = await getNextProblemId();
        if (nextId) {
          console.log('预计使用的下一个题目ID:', nextId);
        }
        
        // 发送请求
        const response = await request('/problem/upload', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(problemForm)
        });
        
        // 显示成功
        ElMessage.success('题目上传成功');
        
        console.log('题目上传响应:', response);
        
        // 获取题目ID
        if (response && response.id) {
          problemId.value = response.id;
          testDataForm.pid = response.id;
          console.log('从响应中获取到题目ID:', response.id);
        } else if (response && typeof response === 'number') {
          problemId.value = response;
          testDataForm.pid = response;
          console.log('响应是数字ID:', response);
        } else {
          console.log('未能从响应中获取题目ID，使用预先获取的下一个ID');
          if (nextId) {
            problemId.value = nextId;
            testDataForm.pid = nextId;
            console.log('使用预先获取的下一个题目ID:', nextId);
            ElMessage.info(`已使用下一个可用题目ID: ${nextId}`);
          } else {
            // 尝试获取最新题目ID
            setTimeout(async () => {
              const latestId = await getLatestProblemId();
              
              if (latestId) {
                const newNextId = latestId + 1;
                problemId.value = newNextId;
                testDataForm.pid = newNextId;
                console.log('获取到新的题目ID:', newNextId);
                ElMessage.info(`已使用下一个可用题目ID: ${newNextId}`);
              } else {
                console.log('未能确定新题目ID');
                // 最后的回退方案：请用户输入题目ID
                promptForProblemId();
              }
            }, 1000);  // 延迟1秒，等待数据库更新
          }
        }
        
        // 进入测试数据上传步骤
        activeStep.value = 3;
        
      } catch (error) {
        console.error('上传出错:', error);
        ElMessage.error('题目上传失败，请检查网络或表单数据');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 提示用户输入题目ID
const promptForProblemId = () => {
  ElMessageBox.prompt('请输入题目ID（可从题目列表页面查看）', '手动输入ID', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\d+$/,
    inputErrorMessage: '请输入有效的数字ID'
  }).then(({ value }) => {
    const manualId = parseInt(value);
    problemId.value = manualId;
    testDataForm.pid = manualId;
    ElMessage.success(`已设置题目ID为: ${manualId}`);
  }).catch(() => {
    ElMessage.info('已取消输入');
  });
};

// 重置题目ID
const resetProblemId = () => {
  ElMessageBox.prompt('请输入题目ID（可从题目列表页面查看）', '更改题目ID', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\d+$/,
    inputErrorMessage: '请输入有效的数字ID',
    inputValue: problemId.value?.toString() || ''
  }).then(({ value }) => {
    const manualId = parseInt(value);
    problemId.value = manualId;
    testDataForm.pid = manualId;
    ElMessage.success(`已更新题目ID为: ${manualId}`);
  }).catch(() => {
    ElMessage.info('已取消更改');
  });
};

// 上传测试数据
const uploadTestData = async () => {
  if (!problemId.value) {
    // 尝试自动获取下一个题目ID
    const nextId = await getNextProblemId();
    if (nextId) {
      problemId.value = nextId;
      testDataForm.pid = nextId;
      ElMessage.info(`已自动设置题目ID为: ${nextId}`);
    } else {
      promptForProblemId();
    }
    return;
  }
  
  try {
    // 输入/输出数据格式验证
    try {
      JSON.parse(testDataForm.input);
      JSON.parse(testDataForm.output);
    } catch (error) {
      ElMessage.error('测试数据必须是有效的JSON格式');
      return;
    }
    
    // 确认题目ID
    await ElMessageBox.confirm(
      `当前正在使用题目ID: ${problemId.value}，确认上传测试数据？`, 
      '确认题目ID',
      {
        confirmButtonText: '确认',
        cancelButtonText: '更改ID',
        type: 'info',
        distinguishCancelAndClose: true,
        closeOnClickModal: false
      }
    );
    
    loading.value = true;
    
    // 确保使用正确的题目ID
    testDataForm.pid = problemId.value;
    console.log('上传测试数据，题目ID:', problemId.value);
    
    // 发送请求
    await request('/problem/uploadData', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(testDataForm)
    });
    
    // 显示成功
    ElMessage.success('测试数据上传成功');
    
    // 清空测试数据表单，方便继续上传
    testDataForm.input = '';
    testDataForm.output = '';
  } catch (error: any) {
    console.error('上传测试数据出错:', error);
    
    // 如果是用户取消操作
    if (error === 'cancel') {
      resetProblemId();
      return;
    }
    
    // 处理上传错误
    ElMessage.error('测试数据上传失败: ' + (error.message || '未知错误'));
    
    // 如果是服务器返回的错误，可能是ID问题
    if (error.status === 500 || error.message?.includes('题目ID')) {
      ElMessageBox.confirm(
        `上传失败，当前题目ID可能不正确。是否尝试使用下一个可用的题目ID？当前ID: ${problemId.value}`, 
        '上传失败',
        {
          confirmButtonText: '使用下一个ID',
          cancelButtonText: '手动设置ID',
          type: 'warning'
        }
      ).then(async () => {
        // 尝试获取下一个可用题目ID
        const nextId = await getNextProblemId();
        if (nextId) {
          problemId.value = nextId;
          testDataForm.pid = nextId;
          ElMessage.success(`已更新题目ID为: ${nextId}`);
        } else {
          ElMessage.error('无法获取下一个可用题目ID');
          resetProblemId();
        }
      }).catch(() => {
        resetProblemId();
      });
    }
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  // 处理时间和内存限制的初始值
  handleTimeLimitChange(timeLimit.value);
  handleMemoryLimitChange(memoryLimit.value);
});
</script>

<style scoped lang="scss">
.problem-upload-container {
  padding: 20px;
  
  .upload-card {
    max-width: 900px;
    margin: 0 auto;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .card-header {
      display: flex;
      flex-direction: column;
      gap: 16px;
      
      h2 {
        margin: 0;
        font-size: 20px;
        color: #303133;
      }
      
      .upload-steps {
        margin-top: 8px;
      }
    }
    
    .problem-form {
      margin-top: 20px;
    }
    
    .form-section-title {
      margin: 24px 0 16px;
      padding-bottom: 8px;
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
    }
    
    .form-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 4px;
    }
    
    .mb-12 {
      margin-bottom: 12px;
    }
    
    .unit-label {
      margin-left: 8px;
      color: #606266;
    }
    
    .json-example {
      margin-top: 8px;
      font-size: 13px;
      
      pre {
        background-color: #f8f8f8;
        padding: 8px;
        border-radius: 4px;
        margin: 4px 0 12px;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      }
      
      .json-example-title {
        font-weight: 500;
        color: #606266;
      }
    }
    
    .step-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      margin-top: 24px;
    }
    
    .test-data-upload {
      margin-top: 20px;
    }
    
    .current-problem-id {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 16px;
      padding: 12px;
      background-color: #ecf5ff;
      border-radius: 4px;
      border-left: 3px solid #409eff;
      font-size: 15px;
    }
    
    .upload-more-actions {
      display: flex;
      justify-content: center;
      gap: 16px;
      margin-top: 24px;
      padding-top: 24px;
      border-top: 1px dashed #dcdfe6;
    }
  }
}
</style> 